﻿//2. Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3
//that has maximal sum of its elements.


using System;
using System.Collections.Generic;

class MaximalSubMatrixSum
{
    static void Main()
    {
        //int numberN = int.Parse(Console.ReadLine());
        //int numberM = int.Parse(Console.ReadLine());
        int[,] matrix = {
            {5, 3, 8, 0, 5},
            {4, 1, 6, 7, 1},
            {3, 9, 4, 9, 8},
            {4, 1, 2, 8, 7},
                        };
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int col = 0; col < matrix.GetLength(1); col++)
            {
                Console.Write(matrix[i, col]);
            }
            Console.WriteLine();
        }

        MaximalSum(matrix);
    }

    static void MaximalSum(int[,] matrix)
    {
        int bestSum = int.MinValue;
        int maxRowIndex = 0;
        int maxColIndex = 0;
        for (int row = 0; row < matrix.GetLength(0) - 2; row++)
        {
            for (int col = 0; col < matrix.GetLength(1) - 2; col++)
            {
                int sum = matrix[row, col] + matrix[row, col + 1] + matrix[row, col + 2]
                    + matrix[row + 1, col] + matrix[row + 1, col + 1] + matrix[row + 1, col + 2]
                    + matrix[row + 2, col] + matrix[row + 2, col + 1] + matrix[row + 2, col + 2];
                if (sum > bestSum)
                {
                    bestSum = sum;
                    maxRowIndex = row;
                    maxColIndex = col;
                }
            }
        }
        Print(matrix, bestSum, maxRowIndex, maxColIndex);
    }

    static void Print(int[,] matrix, int bestSum, int maxRowIndex, int maxColIndex)
    {
        Console.WriteLine("{0}", bestSum);
        for (int i = maxRowIndex; i < maxRowIndex + 3; i++)
        {
            for (int j = maxColIndex; j < maxColIndex + 3; j++)
            {
                Console.Write("{0} ", matrix[i,j]);
            }
            Console.WriteLine();
        }
    }
}
